package org.oc.qaq.service.Impl;

import lombok.extern.slf4j.Slf4j;
import org.oc.qaq.constant.MessageConstant;
import org.oc.qaq.dto.RoleDTO;
import org.oc.qaq.entity.Role;
import org.oc.qaq.entity.UserRole;
import org.oc.qaq.mapper.RoleMapper;
import org.oc.qaq.result.Result;
import org.oc.qaq.service.RoleService;
import org.oc.qaq.vo.RoleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Result<List<RoleVO>> listRoles() {
        List<Role> roles = roleMapper.findAllRoles();
        List<RoleVO> roleVOs = new ArrayList<>();
        roles.forEach(role -> {
            RoleVO roleVO = new RoleVO();
            BeanUtils.copyProperties(role, roleVO);
            roleVO.setTags(roleMapper.findTagsByRoleId(role.getId()));
            roleVOs.add(roleVO);
        });
        return Result.success(roleVOs);
    }

    @Override
    @Transactional
    public Result<?> add(RoleDTO roleDTO) {
        // 插入角色
        Role role = new Role();
        BeanUtils.copyProperties(roleDTO, role);
        roleMapper.insert(role);

        //  插入角色标签
        if (roleDTO.getTagIds() != null && !roleDTO.getTagIds().isEmpty()) {
            roleMapper.insertRoleTags(role.getId(), roleDTO.getTagIds());
        }

        return Result.success();
    }

    @Override
    @Transactional
    public Result<?> update(RoleDTO roleDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleDTO, role);

        roleMapper.update(role);

        roleMapper.deleteRoleTags(roleDTO.getId());
        if (roleDTO.getTagIds() != null && !roleDTO.getTagIds().isEmpty()) {
            roleMapper.insertRoleTags(roleDTO.getId(), roleDTO.getTagIds());
        }

        return Result.success();
    }

    @Override
    public Result<?> delete(Long id) {
        // 先查询当前角色下是否绑定用户
        List<UserRole> users = roleMapper.findRoles(id);
        if (!users.isEmpty()) {
            throw new RuntimeException(MessageConstant.ROLE_RELATED);
        }
        roleMapper.deleteRoleTags(id);
        roleMapper.delete(id);

        return Result.success();
    }

    @Override
    @Transactional
    public Result<?> deleteBatch(List<Long> ids) {
        // 先查询当前角色下是否绑定用户
        ids.forEach(id -> {
            List<UserRole> users = roleMapper.findRoles(id);
            if (!users.isEmpty()) {
                throw new RuntimeException("<UNK>");
            }
            roleMapper.deleteRoleTags(id);
            roleMapper.delete(id);
        });

        return Result.success();
    }
}
